'use strict'
import {
  LoginContainer,
  ForgetPwdContainer,
  GatheringContainer,
  BillContainer,
  MineContainer,
  CreateQRCodeContainer,
  ScanQRCodeContainer,
  MySettingContainer,
  LanchContainer,
  SearchContainer,
  FormContainer,
  ReceiptQRCodeContainer,
  AboutUsContainer,
  BillDetailContainer,
  CommonProblemContainer,
  InputMoneyContainer,
  MessagesContainer,
} from '../containers/index';
import React from 'react';
import TabIcon from '../components/TabIcon';
import {
  Navigator,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
} from 'react-native';
import {
  Router,
  Scene,
  Actions,
} from 'react-native-router-flux';
import { connect } from 'react-redux';
import timer from 'react-native-timer';
import CodePush from 'react-native-code-push';
import JPushModule from 'jpush-react-native';
import * as defaultStyles from '../constants/DefaultStyles';
import {getNowFormatDateAndTime} from '../utils/DateAndTime';
import Speech from 'native-speech';


const RouterWithRedux = connect()(Router);
const receiveCustomMsgEvent = "receivePushMsg";
const receiveNotificationEvent = "receiveNotification";
const getRegistrationIdEvent = "getRegistrationId";

const getSceneStyle = (props, computedProps) => {
  const style = {
    flex: 1,
    backgroundColor: '#fff',
    shadowColor: null,
    shadowOffset: null,
    shadowOpacity: null,
    shadowRadius: null,
  };
  if (computedProps.isActive) {
    style.marginTop = computedProps.hideNavBar ?
      0 : Navigator.NavigationBar.Styles.General.TotalNavHeight;
    style.marginBottom = computedProps.hideTabBar ? 0 : 50;
  }
  return style;
};

/*let NavigationBarRouteMapper = {
  // 左键
  LeftButton(route, navigator, index, navState) {
    console.log(route.name);
    let btnTitle = '<返回';
    if (route.name !== 'register' && route.name.indexOf('quick') < 0) {
        return (
            <View></View>
        );
    } 
    return (
      <TouchableOpacity style={styles.navCon} onPress={()=>navigator.pop()}>
        <Text style={styles.leftBtn}>
            {btnTitle}
        </Text>
      </TouchableOpacity>
    );
  },
  // 右键
  RightButton(route, navigator, index, navState) {
    // ...
  },
  // 标题
  Title(route, navigator, index, navState) {
  }
};*/


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
    }
    this._loadStorage();
  }

  _loadStorage() {
    storage.load({
      key: 'merid',
      autoSync: true,
      syncInBackground: true,
    }).then(ret => {
      console.log(ret);
      if (ret.merid === undefined) {
        timer.setTimeout(
          this, 'push', () => Actions.login({type: 'replace'}), 2000
        );
      }
      else {
        global.merid = ret.merid;
        global.uname = ret.uname;
        global.speech = ret.speech;
        console.log("创建计时器");
        this._getMessages().then(() => {
          console.log(this.state.messages);
          timer.setTimeout(
            this, 'push',() => Actions.tabbar({type: 'replace'}), 2000
          );
        });
      }
    }).catch(err => {
      console.warn(err.message);
      switch (err.name) {
        case 'NotFoundError':
          timer.setTimeout(
            this, 'push', () => Actions.login({type: 'replace'}), 2000
          );
          break;
        case 'ExpiredError':
          break;
      }
    });

  }

  _getMessages() {
    return new Promise((resolve, reject) => {
      storage.load({
        key: merid,
        autoSync: true,
        syncInBackground: true,
      }).then(ret => {
        console.log(ret);
        let arr = [];
        if (ret.messages === undefined) {
          return;
        }
        else {
          this.state.messages = ret.messages;
          resolve();
        }
      }).catch(err => {
        console.warn(err.message);
        switch (err.name) {
          case 'NotFoundError':
            resolve();
            break;
          case 'ExpiredError':
            reject();
            break;
          default:
            reject();
        }
      });
    });
  }

  _addMessage(alertContent: String) {
    let time = getNowFormatDateAndTime('/', ':');
    let message = {
      alertContent: alertContent,
      time: time,
    }
    this.state.messages.push(message);
    storage.save({
      key: merid,
      rawData: {
        messages: this.state.messages,
      },
      expires: null
    });
  }

  componentDidUpdate(nextProps, nextState) {
    console.log("删除计时器");
    timer.clearTimeout(this);
  }


  componentWillUnmount() {

    // if (database) {
    //   database.close(this._closeCB, this._errorCB);
    // }

    JPushModule.setAlias('',
    (success)=> {
      console.log("成功")
    }, (fail) => {
      console.log("失败")
    });
    JPushModule.removeReceiveCustomMsgListener(receiveCustomMsgEvent);
    JPushModule.removeReceiveNotificationListener(receiveNotificationEvent);
    JPushModule.removeGetRegistrationIdListener(getRegistrationIdEvent);

    JPushModule.clearAllNotifications();
    console.log("Will clear all notifications");
  }
  componentDidMount() {
    timer.clearTimeout(this);
    if (!defaultStyles.isIOS) {
      JPushModule.initPush();
    }
    JPushModule.addReceiveCustomMsgListener((map) => {
      this.setState({
        pushMsg: map.message
      });
      console.log("extras: " + map.extras);
    });
    JPushModule.addReceiveNotificationListener((map) => {
      console.log("alertContent: " + map.alertContent);
      console.log("extras: " + map);
      if (speech) {
        Speech.speak('支付金额', () => console.log('播放完成'));
      }
      this._addMessage(map.alertContent);
    });
    JPushModule.addGetRegistrationIdListener((registrationId) => {
      console.log("Device register succeed, registrationId " + registrationId);
    });
    JPushModule.addReceiveOpenNotificationListener((map) => {
      console.log("Opening notification!");
      Actions.messages();
    });
    if(__DEV__){
    }else{
      if (defaultStyles.isIOS) {
        CodePush.sync({
          deploymentKey: 'JbKQwwFZ4txdjJxGXplUNtE0ksNKN162elaOz',
          updateDialog: {
            optionalIgnoreButtonLabel: '稍后',
            optionalInstallButtonLabel: '后台更新',
            optionalUpdateMessage: '有新版本了，是否更新？',
            title: '更新',
            descriptionPrefix:'更新内容：\n',
            mandatoryUpdateMessage:'',
            appendReleaseDescription: true,
          },
          installMode: CodePush.InstallMode.ON_NEXT_RESTART
        });
      }
      else {
        CodePush.sync({
          deploymentKey: 'F2lxzjtVUXFu-JODujOl3L56j0A1N162elaOz',
          updateDialog: {
            optionalIgnoreButtonLabel: '稍后',
            optionalInstallButtonLabel: '后台更新',
            optionalUpdateMessage: '有新版本了，是否更新？',
            title: '更新',
            descriptionPrefix:'更新内容：\n',
            mandatoryUpdateMessage:'',
            appendReleaseDescription: true,
          },
          installMode: CodePush.InstallMode.IMMEDIATE
        });
      }
    }
  }
  render () {
    return (
      /*<Navigator initialRoute={{name: 'login', component: LoginContainer, index: 0}}
        renderScene={(route, navigator) => {
          let Component = route.component;
          return <Component {...route} navigator={navigator}/>
        }}
        navigationBar={
          <Navigator.NavigationBar routeMapper={NavigationBarRouteMapper}/>
        }
        style={styles.navCon}
      />*/
        <RouterWithRedux
        getSceneStyle={getSceneStyle}
        navigationBarStyle={styles.navBar}
        titleStyle={styles.navBarTitle}
      >
        <Scene key="root">
          <Scene key="lanch" component={LanchContainer} hideNavBar hideTabBar initial/>
          <Scene key="login" component={LoginContainer} hideNavBar hideTabBar/>
          <Scene key="forget" component={ForgetPwdContainer} hideNavBar hideTabBar />
          <Scene key="tabbar" tabs pressOpacity={0.8} >
            <Scene
              key="main"
              component={GatheringContainer}
              hideNavBar
              title="收款"
              icon={TabIcon}
              iconName="money"
              save
            />
            <Scene
              key="bill"
              component={BillContainer}
              title="账单"
              icon={TabIcon}
              hideNavBar
              iconName="file-text-o"
            />
            <Scene
              key="mine"
              component={MineContainer}
              title="我的"
              icon={TabIcon}
              hideNavBar
              iconName="user-o"
              save
            />
        </Scene>

          {/*收款*/}
          {/*通知信息*/}
        <Scene key='messages'
               component={MessagesContainer}
               hideNavBar
               hideTabBar
        />
          {/*扫描二维码*/}
        <Scene key='scanPage'
               component={ScanQRCodeContainer}
               hideNavBar
               hideTabBar
        />
          {/*创建二维码*/}
        <Scene key='createQRCode'
               component={CreateQRCodeContainer}
               hideNavBar
               hideTabBar
        />

          {/*账单*/}
          {/*详情*/}
        <Scene key='billDetail'
               component={BillDetailContainer}
               hideNavBar
               hideTabBar
        />
          {/*搜索*/}
        <Scene key='search'
               component={SearchContainer}
               hideNavBar
               hideTabBar
        />
          {/*报表*/}
        <Scene key='form'
               component={FormContainer}
               hideNavBar
               hideTabBar
        />

          {/*我的*/}
          {/*收款二维码*/}
        <Scene key='receiptQRCode'
               component={ReceiptQRCodeContainer}
               hideNavBar
               hideTabBar
        />
          {/*输入金额*/}
        <Scene key='inputMoney'
               component={InputMoneyContainer}
               hideNavBar
               hideTabBar
        />
          {/*设置*/}
        <Scene key='mySetting'
               component={MySettingContainer}
               hideNavBar
               hideTabBar
        />
          {/*关于我们*/}
        <Scene key='aboutUs'
                 component={AboutUsContainer}
                 hideNavBar
                 hideTabBar
        />
          {/*常见问题*/}
        <Scene key='commonProblem'
               component={CommonProblemContainer}
               hideNavBar
               hideTabBar
        />
      </Scene>
      </RouterWithRedux>
    )
  }
}

const styles = StyleSheet.create({
  navCon: {
    flex: 1,
    justifyContent: 'center',
  },
  leftBtn: {
      marginLeft: 10,
      fontSize:16,
      alignSelf: 'center',
      color: 'blue',
  },
  navBar: {
    backgroundColor: '#3e9ce9'
  },
  navBarTitle: {
    color: '#fff',
    fontSize: 20,
  }
})
// export default connect()(App);